package com.zzyl.job;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * wangcong
 * 2025/2/16 17:28
 */
@Component
@Slf4j
public class AlarmDataJob {

    @Autowired
    private AlertRuleService alertRuleService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 * * * * ?")
    public void alarmJob(){
        log.info("开始执行报警任务");


        // 查询所有规则 -- 根据 productKey  , functionId , iotId
        List<AlertRuleVo> list = alertRuleService.queryAllRules(null, null, null);
        if (ObjectUtil.isEmpty(list)){
            return;
        }
        // 从redis获取设备上报的数据
        List<Object> jsonStrList = redisTemplate.opsForHash().values("deviceData:late");
        if (ObjectUtil.isEmpty(jsonStrList)){
            return;
        }
        // 格式化数据 -- 类型转换
        ArrayList<DeviceDataVo> dataList = new ArrayList<>();
        jsonStrList.forEach(json -> {
            dataList.addAll(JSONUtil.toList(json.toString(), DeviceDataVo.class));
        });
        // 遍历数据,匹配规则
        dataList.forEach(deviceDataVo -> {
            alertRuleService.matchRule(deviceDataVo);
        });
        // 报警
    }
}
